package com.itheima.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.sys.entity.CompanyUser;
import com.itheima.sys.entity.Department;
import com.itheima.sys.mapper.DepartmentMapper;
import com.itheima.sys.service.ICompanyUserService;
import com.itheima.sys.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itheima
 * @since 2020-12-13
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private ICompanyUserService companyUserService;

    /**
     * 从员工所在部门依次向上找上级部门ID
     * @param companyUserId
     * @return
     */
    @Override
    public Long[] queryDepartmentsByUserId(Long companyUserId) {
        //1.查询员工信息
        CompanyUser companyUser = companyUserService.getById(companyUserId);
        Long departmentId = companyUser.getDepartmentId();
        if(departmentId==null){
            //如果用户未加入部门，直接返回空
            return null;
        }
        List<Long> departmentList = new ArrayList<>();
        departmentList.add(departmentId);
        while (true) {
            Department department = this.getById(departmentId);
            //2.判断当前用户所属部门是否有上级部门
            if (department != null && department.getParentId() != 0) {
                departmentList.add(department.getParentId());
                //将上级部门作为部门ID再次进行查询
                departmentId = department.getParentId();
            } else {
                break;
            }
        }
        return departmentList.toArray(new Long[]{});
    }
}
